package com.baibei.ebec.user.mine;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;

import com.baibei.ebec.sdk.ApiConstant;
import com.baibei.ebec.sdk.BuildConfig;
import com.baibei.ebec.sdk.TokenInfo;
import com.baibei.ebec.user.R;
import com.baibei.ebec.user.R2;
import com.baibei.model.UserInfo;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicFragment;
import com.baibei.ui.AppUI;
import com.baibei.widget.dialog.ShareDialog;
import com.blankj.utilcode.utils.LogUtils;
import com.rae.swift.session.SessionManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Optional;
import butterknife.Unbinder;

import static com.makeramen.roundedimageview.RoundedDrawable.drawableToBitmap;


/**
 * 我的界面，未登录状态下的
 * Created by ChenRui on 2017/8/3 0003 19:35.
 */
public class MineFragment extends BasicFragment implements View.OnClickListener {

    Unbinder unbinder;

    private Dialog qrDialog;

    public static MineFragment newInstance() {
        return new MineFragment();
    }

    protected UserInfo mUserInfo;

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fm_mine;
    }

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);
        View btnTicket = view.findViewById(R.id.btn_my_tickets);
        View btnRealName = view.findViewById(R.id.btn_realname);
        if (btnTicket != null && btnRealName != null) {
            btnTicket.setOnClickListener(mLoginListener);
            btnRealName.setOnClickListener(mLoginListener);
        }
    }

    /**
     * 登录点击事件
     */
    private View.OnClickListener mLoginListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onLoginClick();
        }
    };


    @Override
    public void onResume() {
        super.onResume();
        mUserInfo = SessionManager.getDefault().getUser();
        if (mUserInfo != null) {
            onLoadUserInfo(mUserInfo);
        }
    }

    public boolean isLogin() {
        return SessionManager.getDefault().isLogin();
    }

    protected void onLoadUserInfo(UserInfo userInfo) {

    }

    @OnClick({R2.id.tv_login_tips, R2.id.img_avatar})
    public void onLoginClick() {
        AppRouter.routeToLogin(getActivity());
    }

    /**
     * 我的账单
     */
    @OnClick(R2.id.btn_bill)
    public void onBillClick() {
        if (isLogin()) {
            AppRouter.routeToBill(getContext());
        } else {
            AppRouter.routeToLogin(getActivity());
        }
    }

    /**
     * 收货地址
     */
    @OnClick(R2.id.btn_address)
    public void onAddressClick() {
        if (isLogin()) {
            AppRouter.routeToOrderAddress(getActivity());
        } else {
            AppRouter.routeToLogin(getActivity());
        }
    }

    /**
     * 设置
     */
    @OnClick(R2.id.btn_setting)
    public void onSettingClick() {
        if (!isLogin()) {
            AppRouter.routeToLogin(getActivity());
        } else {
            AppRouter.routeToSetting(this.getContext());
        }
    }


    /**
     * 分享
     */
    @OnClick(R2.id.btn_share)
    public void onShareClick() {
        if (!isLogin()) {
            AppRouter.routeToLogin(getActivity());
        } else {
            ShareDialog dialog = new ShareDialog(getContext());
            // http://cbecfat.100bei.com/cbclient/index.html?invitationCode=
//            dialog.setShareWeb("http://cbecfat.100bei.com/cbclient/index.html?invitationCode=" + mUserInfo.getInvitationCode(), getString(R.string.share_title), getString(R.string.share_content), null);
            //分享监听，是否安装微信
            dialog.setOnShareClickListener(new ShareDialog.OnShareClickListener() {
                @Override
                public void onShare(Dialog dialog) {
                    dialog.dismiss();
                }

                @Override
                public void onShareFailed(Dialog dialog, String msg) {
                    dialog.dismiss();
                    AppUI.failed(getContext(), msg);
                }
            });
            TokenInfo userToken = SessionManager.getDefault().getUserToken();
            String token = userToken.getAccessToken();
            UserInfo userInfo = SessionManager.getDefault().getUser();
            int userId = userInfo.getUserId();
//            String url = String.format(BuildConfig.API_BASE_URL + "cbclient/index.html?accessToken=" + token,
//                    mUserInfo.getInvitationCode(), BuildConfig.EXCHANGE, ApiConstant.MEMBER_CHANNEL);

            String url = BuildConfig.API_BASE_URL + "ddtj/index.html?invitationCode=" + userId +
                     "&exchange=CB_GUOXIANG&memberChannel=999";
            dialog.setShareWeb(url, getString(R.string.share_title), getString(R.string.share_content), null);
            int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 140, getResources().getDisplayMetrics());
            dialog.setInvitationCode(mUserInfo.getInvitationCode());
            dialog.show();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * 我的分享二维码
     */
    @OnClick(R2.id.btn_myQR)
    public void onMyQRClicked() {
        if (!isLogin()) {
            AppRouter.routeToLogin(getActivity());
            return;
        }
        qrDialog = new Dialog(getContext());
        Window window = qrDialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        qrDialog.setContentView(R.layout.dialog_qr);
        ImageView ivClose = qrDialog.findViewById(R.id.iv_close);
        ImageView ivQR = qrDialog.findViewById(R.id.iv_QR);

        UserInfo userInfo = SessionManager.getDefault().getUser();
        int userId = userInfo.getUserId();
        String shareUrl = BuildConfig.API_BASE_URL + "ddtj/index.html?invitationCode=" + userId +
                "&exchange=CB_GUOXIANG&memberChannel=999";
//        ivQR.setImageBitmap(QRCode.createQRCode(shareUrl));
        ivQR.setImageBitmap(QRCode.createQRCodeWithLogo6(shareUrl, 500, drawableToBitmap(getResources().getDrawable(R.drawable.ic_logo))));

        ivClose.setOnClickListener(this);

        qrDialog.setCanceledOnTouchOutside(false);
        qrDialog.show();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.iv_close) {
            qrDialog.dismiss();
        }
    }
}
